package martian.t1me.core
{
	import flash.events.Event;
	import flash.events.EventDispatcher;

	public class Sequence extends EventDispatcher implements Pausable
	{
		static public const START:String = "sequenceEventStart";
		static public const STEP:String = "sequenceEventStep";
		static public const STOP:String = "sequenceEventStop";
		
		
		static public const STOPPED:int = 0;
		static public const PAUSED:int = 1;
		static public const RUNNING:int = 2;
		
		
		public var stack:Vector.<Sequencable>;		
		private var i:int = -1;
			public function get index():int { return i - 1; }
			public function get current():Sequencable { return i >= 0 ? stack[i] : null; }
		
		private var s:int = 0;
			public function get status():int { return s; }
		
		private var p:Boolean = false;
		
		
		public function Sequence() { stack = new Vector.<Sequencable>(); }
		
		public function start():void
		{
			if (s == STOPPED)
			{
				i = 0;
				dispatchEvent(new Event(START));
				step();
				s = RUNNING;
			}
		}
		
		private function stop():void
		{
			if (s == RUNNING)
			{
				i = 0;
				dispatchEvent(new Event(STOP));
				s = STOPPED;
			}
		}
		
		public function pause():void
		{
			if (s == RUNNING)
			{
				p = true;
				s = PAUSED;
			}
		}
		
		public function resume():void
		{
			if (s == PAUSED)
			{
				p = false;
				step();
				s = RUNNING;
			}
		 }
		
		private function step(e:Event = null):void
		{
			if (e != null) { e.target.removeEventListener(STOP, step); }
			
			if (p) { return; }
			
			if (i < stack.length)
			{
				stack[i].addEventListener(STOP, step);
				stack[i].start();
				
				dispatchEvent(new Event(STEP));
				i++;
			}
			else { stop(); }
		}
	}
}